package cn.yangyumanage.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import cn.yangyumanage.R;
import cn.yangyumanage.adapter.BannerManageRvAdapter;
import cn.yangyumanage.bean.Banner;
import cn.yangyumanage.bean.Film;
import cn.yangyumanage.bean.Page;
import cn.yangyumanage.callback.DataCallBack;
import cn.yangyumanage.http.HttpClient;
import cn.yangyumanage.model.BannerHttpModel;
import cn.yangyumanage.util.ToastUtil;
import cn.yangyumanage.util.Utils;
import cn.yangyumanage.util.ViewUtil;


public class BannerFragment extends Fragment {
    private View view;
    private Activity activity;
    private final BannerHttpModel httpModel = new BannerHttpModel();
    private RecyclerView rv_banner;
    private LinearLayout ll_add_banner;

    private AlertDialog.Builder builder;
    private List<Film> records;
    private final List<String> nameList = new ArrayList<>();
    private SmartRefreshLayout srl_banner;
    private final List<Banner> bannerList = new ArrayList<>();
    private final BannerManageRvAdapter adapter;

    public BannerFragment(Activity activity) {
        this.activity = activity;
        builder = new AlertDialog.Builder(activity);
        adapter = new BannerManageRvAdapter(activity, bannerList);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_banner, container, false);
        initView();
        initData();
        return view;
    }

    private void initData() {
        getAllBanner();
    }

    private void initView() {
        rv_banner = view.findViewById(R.id.rv_banner);
        rv_banner.setAdapter(adapter);
        rv_banner.setLayoutManager(new LinearLayoutManager(activity));
        ll_add_banner = view.findViewById(R.id.ll_add_banner);
        ll_add_banner.setOnClickListener(new View.OnClickListener() {
            private ColorStateList blueColorStateList = AppCompatResources.getColorStateList(activity, R.color.blue);

            @Override
            public void onClick(View v) {
                View bannerView = View.inflate(activity, R.layout.edittext_banner_add, null);
                EditText et_search = bannerView.findViewById(R.id.et_search);
                TextView tv_search = bannerView.findViewById(R.id.tv_search);
                Spinner sp_banner = bannerView.findViewById(R.id.sp_banner);
                EditText et_banner_post_url = bannerView.findViewById(R.id.et_banner_post_url);
                et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        //监听搜索键
                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                            String searchContent = et_search.getText().toString();
                            ViewUtil.hideOneInputMethod(activity, et_search);
                            if (searchContent.equals("")) {
                                et_search.clearFocus();
                                return false;
                            }
                            fuzzyQuery(-1, -1, searchContent, sp_banner);
                            et_search.clearFocus();
                            return true;
                        }
                        return false;
                    }
                });
                tv_search.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String searchContent = et_search.getText().toString();
                        ViewUtil.hideOneInputMethod(activity, et_search);
                        if (searchContent.equals("")) {
                            et_search.clearFocus();
                            return;
                        }
                        fuzzyQuery(-1, -1, searchContent, sp_banner);
                        et_search.clearFocus();
                    }
                });
                builder.setTitle("横幅添加");
                builder.setPositiveButton("添加", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (sp_banner.getSelectedItemPosition() == -1) {
                            ToastUtil.show(activity, "未选择影片");
                            return;
                        }
                        String postUrl = et_banner_post_url.getText().toString();
                        if (postUrl.equals("")) {
                            ToastUtil.show(activity, "未添加Url");
                            return;
                        }
                        Banner banner = new Banner();
                        String name = sp_banner.getSelectedItem().toString();
                        int index = nameList.indexOf(name);
                        Integer id = records.get(index).getId();
                        banner.setFilmId(id);
                        banner.setPostUrl(postUrl);
                        addBanner(banner);
                    }
                });
                builder.setNegativeButton("取消", null);
                AlertDialog dialog = builder.create();
                dialog.setView(bannerView);
                // 设置其他区域不关闭窗口
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(blueColorStateList);
            }
        });
        srl_banner = view.findViewById(R.id.srl_banner);
        srl_banner.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getAllBanner();
            }
        });
    }

    //获取所有横幅信息
    private void getAllBanner() {
        httpModel.getAllBanner(new DataCallBack() {
            @Override
            public void getData(Object data) {
                List<Banner> banners = Utils.<Banner>objectToList(data);
                bannerList.clear();
                bannerList.addAll(banners);
                HttpClient.handler.post(new Runnable() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                        srl_banner.finishRefresh();
                    }
                });
            }
        });
    }

    //模糊查询
    private void fuzzyQuery(int currentPage, int pageSize, String queryContent, Spinner spinner) {
        httpModel.fuzzyQuery(currentPage, pageSize, queryContent, new DataCallBack() {
            @Override
            public void getData(Object data) {
                Page page = (Page) data;
                records = page.getRecords();
                nameList.clear();
                for (Film record : records) {
                    nameList.add(record.getName());
                }
                ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(activity, R.layout.item_select, nameList);
                HttpClient.handler.post(() -> {
                    spinner.setAdapter(arrayAdapter);
                    spinner.setSelection(0);
                    arrayAdapter.setDropDownViewResource(R.layout.item_dropdown);
                });
            }
        });
    }

    //添加横幅信息
    private void addBanner(Banner banner) {
        httpModel.addBanner(banner, new DataCallBack() {
            @Override
            public void getData(Object data) {
                Boolean flag = (Boolean) data;
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (flag) {
                            ToastUtil.show(activity, "添加成功");
                            srl_banner.autoRefresh();
                        } else {
                            ToastUtil.show(activity, "添加失败");
                        }
                    }
                });
            }
        });
    }
}